import Taro from '@tarojs/taro'
import React, { Component } from 'react'
import {
  View, Button, Text, Image, Label, Checkbox, CheckboxGroup
} from '@tarojs/components'
import { connect } from 'react-redux'
import Images from '@ASSET/Images'
import authActions from '@ACTIONS/auth'
import Navigate from '@NAVIGATION/navigateManager'
import { getPlatform } from '@UTILS/common'
import { getJsCode } from '@UTILS/wx'
import './index.scss'

@connect(
  null,
  authActions
)
class Index extends Component {
  state = {
    btnDisabled: false,
  }

  componentDidMount() {
    this.initLoginCode();
  }

  code = ''

  initLoginCode = async () => {
    const code = await getJsCode(true);
    this.code = code;
  }

  goMobileLogin = () => {
    Navigate.loginByPhone()
  }

  onGetPhoneNumber = async e => {
    const phoneData = e.detail
    if (phoneData.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv } = phoneData
      const code = await getJsCode()
      const payload = { encrypted_data: encryptedData, iv, code }
      const data = { payload }
      this.props.dispatchLoginWeiXin(data)
    } else if (phoneData.errMsg !== 'getPhoneNumber:fail user deny') {
      Taro.showModal({
        title: '登录失败',
        confirmColor: '#47C690',
        cancelColor: '#595959',
        content: '详情可咨询客服',
        showCancel: false,
      })
    }
  }

  onChangePrivate = e => {
    this.setState({
      btnDisabled: !e.detail.value.length
    })
  }

  onOpenPolicy=e => {
    e?.stopPropagation?.()
    Navigate.policy()
  }

  onOpenAgreement = e => {
    e?.stopPropagation?.()
    Navigate.agreement()
  }

  render() {
    const { btnDisabled } = this.state
    const { isWeb } = getPlatform()
    return (
      <View className={`auth-container ${isWeb ? 'auth-web-container' : ''}`}>
        <View className="logo-container">
          <Image className="logo" src={Images.logo} />
        </View>
        <View className="opt">
          <Button type="primary" plain="true" className="phone-button button" onClick={this.goMobileLogin} disabled={btnDisabled}>
            手机号码登录
          </Button>
          <Button
            type="primary"
            className="wechat-button button"
            open-type="getPhoneNumber"
            onGetPhoneNumber={this.onGetPhoneNumber}
            disabled={btnDisabled}
          >
            微信登录
          </Button>
          <View className="checkBox-container">
            <Label>
              <CheckboxGroup onChange={this.onChangePrivate}>
                <Checkbox checked value={1} className="circle-checkbox" />
              </CheckboxGroup>
            </Label>
            我已同意
            <Text onClick={this.onOpenAgreement} className="checkbox-link">疼爱健康用户协议</Text>
            <Text>及</Text>
            <Text className="checkbox-link" onClick={this.onOpenPolicy}>隐私政策</Text>
          </View>

        </View>
      </View>
    )
  }
}

export default Index
